package com.ay.weixin.fdc.front.usercenter.event.old;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Date;

import javax.servlet.ServletException;

import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.intercepter.Before;
import org.lizar.controller.loader.BasicLoader;
import org.lizar.controller.loader.EventLoader;
import org.lizar.controller.loader.FilePostForm;
import org.lizar.ioc.Container;
import org.lizar.util.MyMath;
import org.lizar.util.StringHelper;

import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.config.types.UserStatus;
import com.ay.weixin.config.types.UserType;
import com.ay.weixin.fdc.boss.user.db.FDCAgentDao;
import com.ay.weixin.fdc.boss.user.domain.Activity;
import com.ay.weixin.fdc.boss.user.domain.FDCAgent;
import com.ay.weixin.fdc.boss.user.domain.FDCUserCenter;
import com.ay.weixin.fdc.boss.user.domain.UserBasic;
import com.ay.weixin.fdc.boss.user.domain.UserCenter;
import com.ay.weixin.fdc.boss.yongjin.db.IbatisCashFlow;
import com.ay.weixin.fdc.boss.yongjin.domain.CashFlow;
import com.ay.weixin.fdc.front.usercenter.event.UserEvent;

/**
 * 
 * 
 * */
public class Register extends Event implements Before{
	private FDCAgentDao user_dao;
	private IbatisCashFlow cash_dao;
	private UserEvent user_event;
	private FDCUserCenter user_center;
	private com.ay.weixin.fdc.front.usercenter.event.manager.Register register;
	@Override
	public void init_property() throws Exception {
		
		user_dao=Container.get(FDCAgentDao.class);
		cash_dao=Container.get(IbatisCashFlow.class);
		user_event=Container.get(UserEvent.class);
		register=Container.get(com.ay.weixin.fdc.front.usercenter.event.manager.Register.class);
		user_center=Container.get(FDCUserCenter.class);
	}

	@Override
	public void before(BasicLoader bl) throws ServletException, IOException {
		long wxproject_id=bl.queryPathInt(3);
		bl.setAttr("need_id_card_no", ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_id_card_no"));
		bl.setAttr("need_old_house", ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_old_house"));
		bl.setAttr("user_type", UserType.old.name());
	}
	
	@Override
	public String default_handling_path() {
		return "/fdc/register/old/*";
	}

	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		long wxproject_id=el.queryPathInt(3);
		System.out.println("project_id:"+wxproject_id);
		
		register.handle(el,wxproject_id);
	}
	
	public void try_register(EventLoader el,long wxproject_id) throws IOException, ServletException{
		if(el.queryPathCheck(4,"submit")){
			submit(el,wxproject_id);
		}else{
			view(el,wxproject_id);
		}
	}
	
	private void view(EventLoader el,long wxproject_id) throws IOException, ServletException{
		UserEvent.load_vcode_check(el,wxproject_id);
		el.template("/WEB-INF/template/app/"+wxproject_id+"/fdc/register.vm");
	}
	
	private void submit(EventLoader el,long wxproject_id) throws IOException, ServletException{
		if(!el.isMultipartContent()){
			el.text("invalid visit.");
			return;
		}
		UserEvent.inc_vcode_check(el,wxproject_id);
		FilePostForm file=el.parseFilePostForm(ProjectConfig.getLong(wxproject_id,"sys.max_image_file_size")*1024);
		file.setAllParamToAttr(el);
		String name=file.getStr("name");
		String password=file.getStr("password");
		String phone=file.getStr("phone");
		String house=file.getStr("house");
		String vcode=file.getStr("vcode");
		String id_card_no=file.getStr("id_card_no");
		file.setAllParamToAttr(el);
		String msg=null;
		if(file.getErrorMsg()!=null){
	        msg=file.getErrorMsg();
	        el.setAttr("msg",msg);
	        view(el,wxproject_id);
	       return;
	    }
		
		boolean need_vcode=el.getSessionAttr("tel_vcode", 0)>=ProjectConfig.getInt(wxproject_id,"fdc_usercenter.vcode_used_error_in_times");
		if(need_vcode&&el.getSessionAttr("vcode")!=null&&!StringHelper.equals(vcode.toLowerCase(), el.getSessionAttr("vcode").toString().toLowerCase())){
			msg=el.i18("login.vcode_invalid");
			el.setAttr("msg",msg);
	        view(el,wxproject_id);
			return;
		}
		
		if(StringHelper.isNull(phone)||!StringHelper.isLong(phone)){
			msg=String.format(el.i18("fdc_usercenter.phone.not.valid"), Keys.getInt("fdc_usercenter.register_phone_length"));
			el.setAttr("msg",msg);
	        view(el,wxproject_id);
			return;
		}
		if(StringHelper.isNull(password)||!StringHelper.isLong(password)||password.length()>Keys.getInt("fdc_usercenter.register_password_max_length")||password.length()<Keys.getInt("fdc_usercenter.register_password_min_length")){
			msg=String.format(el.i18("fdc_usercenter.password.not.valid"), Keys.getInt("fdc_usercenter.register_password_min_length"),Keys.getInt("fdc_usercenter.register_password_max_length"));
			el.setAttr("msg",msg);
	        view(el,wxproject_id);
			return;
		}
		
		if(StringHelper.isNull(name)||name.length()>Keys.getInt("fdc_usercenter.register_name_max_length")||name.length()<Keys.getInt("fdc_usercenter.register_name_min_length")){
			msg=String.format(el.i18("fdc_usercenter.name.not.valid"), Keys.getInt("fdc_usercenter.register_name_min_length"),Keys.getInt("fdc_usercenter.register_name_max_length"));
			el.setAttr("msg",msg);
	        view(el,wxproject_id);
			return;
		}
		
		if(StringHelper.isNull(house)){
			msg=el.i18("fdc_usercenter.house.cannotbe.empty");
			el.setAttr("msg",msg);
		    view(el,wxproject_id);
			return;
		}
		
		if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_id_card_no")){
			
			try {
				msg=UserEvent.IDCardValidate(id_card_no);
			} catch (ParseException e) {
				msg=String.format(el.i18("fdc_usercenter.id_card_no.notvalid"));
				el.setAttr("msg",msg);
			    view(el,wxproject_id);
				return;
			}
			if(StringHelper.isNull(id_card_no)||StringHelper.isNotNull(msg)){
				msg=String.format(el.i18("fdc_usercenter.id_card_no.notvalid"));
				el.setAttr("msg",msg);
			    view(el,wxproject_id);
				return;
			}else{
				try {
					if(user_dao.getByIDCardNo(wxproject_id,id_card_no)!=null){
						msg=String.format(el.i18("fdc_usercenter.id_card_no.exists"));
						el.setAttr("msg",msg);
					    view(el,wxproject_id);
						return;
					}
				} catch (SQLException e) {
					e.printStackTrace();
					el.setAttr("msg",el.i18("fdc_usercenter.server_error"));
			        view(el,wxproject_id);
					return;
				}
			}
		}
		
		try {
			if(user_dao.phoneExists(wxproject_id,phone)){
				msg=el.i18("fdc_usercenter.phone.already.exists");
				el.setAttr("msg",msg);
			    view(el,wxproject_id);
				return;
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
			el.setAttr("msg",el.i18("fdc_usercenter.server_error"));
	        view(el,wxproject_id);
			return;
		}
		
		
		FDCAgent user=new FDCAgent();
		user.setName(name);
		user.setPassword(MyMath.encryptionWithMD5(password));
		user.setPhone(phone);
		user.setHouse(house);
		user.setType(UserType.old.name());
		user.setId_card_no(id_card_no);
		user.setWxproject_id(wxproject_id);
		if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_verify_manually")){
			user.setProfile_verify(UserBasic.PROFILE.NOT_VERIFY.getValue());
			user.setStatus(UserStatus.apply.name());
		}else{
			user.setProfile_verify(UserBasic.PROFILE.VERIFIED.getValue());
			user.setStatus(UserStatus.ok.name());
		}
		
		user.setCreate_time(new Date(System.currentTimeMillis()));
		try{
			user_dao.insert(user);
			user=user_dao.getByPhone(wxproject_id,phone);
			user.setInvite_code(UserCenter.getInviteCode(user.getId()));
			user_dao.updateInviteCode(user.getId(),user.getInvite_code());
		}catch(Exception e){
			e.printStackTrace();
			el.setAttr("msg",el.i18("fdc_usercenter.server_error"));
	        view(el,wxproject_id);
			return;
		}
		
		if(!ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_verify_manually")){
			register_income(el,wxproject_id,user);
		}
		
		el.setSessionAttr("user",user);
		UserEvent.setSessionTimeOut(el);
		el.setSessionAttr("registered",true);
		UserEvent.clean_vcode(el);
		user_event.update_weixin(el,user.getId());
		user_center.setSession(user.getId(), el.getSession());
		el.response_to_root("/fdc/usercenter/"+wxproject_id);
	}
	
	private void register_income(EventLoader el,long wxproject_id,FDCAgent user){
		float register_value=0;
		try {
			if(user_dao.hasRegisterRecord(user.getId())){
				return;
			}
			user.setRegister_reward(UserBasic.REGISTER_REWARD_TRUE);
			user_dao.updateRegisterReward(user.getId());
		} catch (SQLException e1) {
			e1.printStackTrace();
			return;
		}
		if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_benifit_for_new_commer")){
			if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_confirm_benifit")){
				register_value=ProjectConfig.getFloat(wxproject_id,"fdc_usercenter.register_benifit_value");
			}else{
				String result=Activity.activity_cash_rules(ProjectConfig.getStr(wxproject_id,"fdc_usercenter.register_invate_benifit_rules"));
				try{
					register_value=Float.parseFloat(result);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			CashFlow mycash=new CashFlow();
			mycash.setCash(register_value);
			mycash.setFrom_user_id(0);
			mycash.setReason(Keys.getStr("fdc_usercenter.register_return"));
			mycash.setTimestamp(System.currentTimeMillis());
			mycash.setUser_id(user.getId());
			try {
				cash_dao.insert(mycash);
			} catch (SQLException e) {
				e.printStackTrace();
				el.setSessionAttr("user",user);
			}
			el.setAttr("cash",mycash);
		}
		
		
	}
	
	
}
